package krillr.Util;
import java.util.*;
import robocode.*;

public final class BattlefieldTracker extends Module {
    private HashMap units;
    private KrillBot bot;
    public SelfTracker parentTracker;
    
    public BattlefieldTracker(KrillBot b) {
        bot = b;
        units = new HashMap();
        parentTracker = new SelfTracker(b);
    }
    
    public void run() {
        parentTracker.update();
        Iterator it = units.keySet().iterator();
        UnitTracker best = null;
        while(it.hasNext()) {
            UnitTracker unit = (UnitTracker)units.get(it.next());
            double dangerFactor = (unit.guessDistance()*0.2) % (unit.energy()*0.8);
            unit.setDangerFactor(dangerFactor);
            unit.run();
        }
    }
    
    public void addUnit(ScannedRobotEvent e) {
        UnitTracker unit;
        if(units.containsKey(e.getName()) == false)
            unit = new UnitTracker(e, bot);
        else {
            unit = (UnitTracker)units.get(e.getName());
            unit.update(e);
        }
        units.put(e.getName(), unit);
    }
    
    public void removeUnit(String unitName) {
        if(units.containsKey(unitName))
            units.remove(unitName);
    }
    
    public boolean hasUnit(String unitName) {
        return units.containsKey(unitName);
    }
    
    public UnitTracker getUnit(String unitName) {
        if(units.containsKey(unitName))
            return (UnitTracker)units.get(unitName);
        return new UnitTracker();
    }
    
    public final UnitTracker getBestEnemy() {
        Iterator it = units.keySet().iterator();
        UnitTracker best = null;
        while(it.hasNext()) {
            UnitTracker unit = (UnitTracker)units.get(it.next());
            if(best == null) { best = unit; }
            else if(best.dangerFactor() > unit.dangerFactor()) { best = unit; }
        }
        return best;
    }
    
    public HashMap units() { return units; }
}